package com.spring.sunflower.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupAnimation;
import com.spring.sunflower.R;
import com.spring.sunflower.common.LogOutActivity;
import com.spring.sunflower.dialog.OnPermissionIntroClickListener;
import com.spring.sunflower.dialog.PermissionIntroDialog;
import com.spring.sunflower.http.AppRetrofit;
import com.spring.sunflower.util.LocationUtils;
import com.tencent.imsdk.v2.V2TIMAdvancedMsgListener;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMMessageReceipt;
import com.umeng.analytics.MobclickAgent;

import java.util.List;


/**
 * Created by Kevin on 2017/3/17.
 * Blog:http://blog.csdn.net/student9128.m
 * Description:
 */

public abstract class BaseCompatFragment extends AppBaseFragment implements BaseView {
    protected View mView;
    private boolean isViewCreated = false;
    private boolean isUIVisible = false;
    protected Bundle args;

    //    private BaseDialog mProgressDialog;
//    private BaseDialog mFingerprintDialog;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
            Bundle savedInstanceState) {
        mView = inflater.inflate(setLayoutResId(), container, false);
        initView();
        initData();
        initListener();
//        printI("onCreateVew===========");
//        if (getUserVisibleHint()) {
//            isUIVisible = true;
//            lazyLoad();
//        } else {
//            isUIVisible = false;
//        }
        return mView;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        printI("onAttach===========");
    }

    @Override
    public void onStart() {
        super.onStart();
//        refreshUI();
        if (getUserVisibleHint()) {
            isUIVisible = true;
            lazyLoad();
        } else {
            isUIVisible = false;
        }
//        printI("onStart===============");
    }

    @Override
    public void onResume() {
        super.onResume();
//        printI("onResume=======");
    }

    @Override
    public void onPause() {
        super.onPause();
//        printI("onPause=====");
    }

    @Override
    public void onStop() {
        super.onStop();
//        printD("onStop======");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        printE("onDestroy=======");

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        printI("onCreate==============");
        args = getArguments();
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        printI("onActivityCreated============");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        printI("onDestroyView===========" + getClass().getSimpleName());
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewCreated = true;
        lazyLoad();
//        printI("onViewCreated==========");
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            isUIVisible = true;
            lazyLoad();
        } else {
            isUIVisible = false;
        }
    }

    public String getDisposableKey() {
//        return mActivity.getPackageName()+SEP+TAG;
        return getClass().getName();
    }

    private void lazyLoad() {
//        printD(isUIVisible + "============isUIVisible");
//        printD(isViewCreated + "------------isViewCreated");
        if (isViewCreated && isUIVisible) {
//            mPresenter.requestData();
            loadData();
            isUIVisible = false;
            isViewCreated = false;
        }
    }

    /**
     * set Layout Resource Id
     *
     * @return
     */
    public abstract int setLayoutResId();

    public abstract void initView();

    public abstract void initData();

    public abstract void initListener();

    public abstract void loadData();

    /**
     * refresh user interface.
     */
//    public abstract void refreshUI();

    /**
     * 创建fragment的静态方法，方便传递参数
     *
     * @param args 传递的参数
     * @return
     */
    public static <T extends Fragment> T newInstance(Class clazz, Bundle args) {
        T mFragment = null;
        try {
            mFragment = (T) clazz.newInstance();
        } catch (java.lang.InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        mFragment.setArguments(args);
        return mFragment;
    }

    //===============Some Methods=================//
    public void startNewActivity(Class<? extends BaseActivity> clazz) {
        startActivity(new Intent(mActivity, clazz));
    }


    public void showLoadingDialog() {
        showLoadingDialog("");
    }

    public void showLoadingDialog(String title) {
        printD("showLoadingDialog");
//        if (mProgressDialog != null || mActivity.isFinishing()) {
//            return;
//        }
//        if (mProgressDialog == null) {
//            mProgressDialog = DialogManager.createProgressDialog(title);
//            mProgressDialog.show(getFragmentManager(), "ProgressDialog");
//        }

//        showFragmentDialog(mProgressDialog,"ProgressDialog");
    }

    public void dismissLoadingDialog() {
        printD("dismissLoadingDialog");
//        if (mProgressDialog != null) {
////            if (mProgressDialog.isAdded()) {
////                mProgressDialog.dismiss();
//            }
//            mProgressDialog = null;
    }
//        if (mProgressDialog != null && !mActivity.isFinishing()) {
//            if (mProgressDialog.isAdded()) {
//                mProgressDialog.dismiss();
//            } else {
//                mProgressDialog.dismissAllowingStateLoss();
//            }
//            mProgressDialog = null;
//        }
//    }

    public void showFingerprintDialog() {
//        if (mFingerprintDialog != null || mActivity.isFinishing()) {
//            return;
//        }
//        mFingerprintDialog = DialogManager.createFingerprintDialog();
//        showFragmentDialog(mFingerprintDialog, "FingerprintDialog");
    }

    public void dismissFingerprintDialog() {
//        if (mFingerprintDialog != null && !mActivity.isFinishing()) {
//            if (mFingerprintDialog.isAdded()) {
//                mFingerprintDialog.dismiss();
//            }
//        }
    }

    public void showFragmentDialog(DialogFragment dialog, String tag) {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(dialog, tag);
        ft.commitAllowingStateLoss();
    }

    //    @Override
//    public void showAlertDialog(String title, String content, DialogBtnClickListener listener) {
//        DialogContract dialogContract = (DialogContract) mActivity;
//        if (dialogContract != null && !isDetached()) {
//            dialogContract.showAlertDialog(title, content, listener);
//        }
//    }

    //    @Override
//    public void showAlertDialog(String title, String content) {
//        showAlertDialog(title, content, null);
//    }

    //    @Override
//    public void showAlertDialog(int titleResId, int contentResId, DialogContract
//            .DialogBtnClickListener listener) {
//        DialogContract dialogContract = (DialogContract) mActivity;
//        if (dialogContract != null && !isDetached()) {
//            dialogContract.showAlertDialog(titleResId, contentResId, listener);
//        }
//    }

    //    //    @Override
//    public void showAlertDialog(int titleResId, int contentResId) {
//        DialogContract dialogContract = (DialogContract) mActivity;
//        if (dialogContract != null && !isDetached()) {
//            dialogContract.showAlertDialog(titleResId, contentResId);
//        }
//    }
//
//    //    @Override
//    public void showNormalDialog(int titleResId, int contentResId, DialogContract
//            .DialogBtnClickListener listener) {
//        DialogContract dialogContract = (DialogContract) mActivity;
//        if (dialogContract != null && !isDetached()) {
//            dialogContract.showNormalDialog(titleResId, contentResId, listener);
//        }
//    }
//
//    //    @Override
//    public void showNormalDialog(String title, String content, int negativeBtn, int positiveBtn,
//                                 DialogContract.DialogBtnClickListener listener) {
//        DialogContract dialogContract = (DialogContract) mActivity;
//        if (dialogContract != null && !isDetached()) {
//            dialogContract.showNormalDialog(title, content, negativeBtn, positiveBtn, listener);
//        }
//    }
    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showError(String msg) {
//        if ("无效的token".equals(msg)) {
//            Intent intent = new Intent(mActivity, LoginActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//            startActivity(intent);
//        }
        showToast(msg);
    }

    @Override
    public void showError(int errorCode, String msg) {

    }

    @Override
    public void onErrorCode(BaseModel model) {

    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void onProgress(int progress) {

    }

    @Override
    public void requestFinish() {

    }

    @Override
    public void requestFinishWithSth(String type) {

    }

    @Override
    public void showTokenExpired() {
        MobclickAgent.onProfileSignOff();
        showToast("登录已失效，请重新登录");
        LocationUtils.getInstance(mActivity).stop();
        AppRetrofit.destroy();
        BaseFragment.mStrangeListData.clear();
        clearStorageUserData();
        goLoginActivity();
    }

    @Override
    public void showNeedCharge() {

    }

    private void goLoginActivity() {
        V2TIMManager.getMessageManager().removeAdvancedMsgListener(new V2TIMAdvancedMsgListener() {
            @Override
            public void onRecvNewMessage(V2TIMMessage msg) {
                super.onRecvNewMessage(msg);
            }

            @Override
            public void onRecvC2CReadReceipt(List<V2TIMMessageReceipt> receiptList) {
                super.onRecvC2CReadReceipt(receiptList);
            }

            @Override
            public void onRecvMessageRevoked(String msgID) {
                super.onRecvMessageRevoked(msgID);
            }

            @Override
            public void onRecvMessageModified(V2TIMMessage msg) {
                super.onRecvMessageModified(msg);
            }
        });
        V2TIMManager.getInstance().logout(new V2TIMCallback() {
            @Override
            public void onError(int i, String s) {
            }

            @Override
            public void onSuccess() {
                V2TIMManager.getInstance().unInitSDK();
            }
        });
        Intent intent = new Intent(mActivity, LogOutActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
//        forbiddenBackKey = true;
    }

    public void showPermissionIntroDialog(BasePopupView popupView) {
        new XPopup.Builder(mActivity)
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .isRequestFocus(false)
                .asCustom(popupView)
                .show();
    }

    public void showPermissionIntroDialog(String title, String desc, OnPermissionIntroClickListener listener) {
        PermissionIntroDialog dialog = new PermissionIntroDialog(mActivity, R.layout.dialog_permission_intro, listener);
        dialog.setOnCreateViewListener(new PermissionIntroDialog.OnCreateViewListener() {
            @Override
            public void onCreateView() {
                TextView tvTitle = dialog.findViewById(R.id.tvTitle);
                TextView tvDesc = dialog.findViewById(R.id.tvDesc);
                tvTitle.setText(title);
                tvDesc.setText(desc);
            }
        });
        new XPopup.Builder(mActivity)
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .isRequestFocus(false)
                .asCustom(dialog)
                .show();
    }

    public void showPermissionIntroDialog(String[] titleArr, String[] descArr, OnPermissionIntroClickListener listener) {
        PermissionIntroDialog dialog = new PermissionIntroDialog(mActivity, R.layout.dialog_permission_intro_list, listener);
        dialog.setOnCreateViewListener(new PermissionIntroDialog.OnCreateViewListener() {
            @Override
            public void onCreateView() {
                LinearLayout container = dialog.getContainer();
                for (int i = 0; i < titleArr.length; i++) {
                    View inflate = View.inflate(mActivity.getBaseContext(), R.layout.dialog_permission_intro_content_item, null);
                    TextView tvTitle = inflate.findViewById(R.id.tvTitle);
                    TextView tvDesc = inflate.findViewById(R.id.tvDesc);
                    tvTitle.setText(titleArr[i]);
                    tvDesc.setText(descArr[i]);
                    container.addView(inflate);
                }
            }
        });

        new XPopup.Builder(mActivity)
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .isRequestFocus(false)
                .asCustom(dialog)
                .show();
    }
}